package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.dto.HistorySearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.utils.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    public void insert(String keyword, Long userId) {
        log.info("线程池异步调度开始执行，线程名字：{}", Thread.currentThread().getName());
        if (StringUtils.isEmpty(keyword)) {
            return;
        }
        //1.查询当前用户搜索的关键词
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.存在，更新时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3.不存在，判断当前历史记录是否超过10条
        Query query1 = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> userSearchList = mongoTemplate.find(query1, ApUserSearch.class);

        //3.1不超过 保存记录
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId.intValue());
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());
        if (userSearchList == null || userSearchList.size() < 10) {
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.2超过 替换掉最久的记录
        ApUserSearch userSearch = userSearchList.get(userSearchList.size() - 1);
        mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(userSearch.getId())), apUserSearch);
    }

    /**
     * 加载历史搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {

        Long userId = AppThreadLocalUtil.getId();
        //判断用户是否登录，登录才能获取搜索记录
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构造查询条件
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(list);
    }

    /**
     * 删除搜索记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1.参数校验
        if (dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.登录判断
        Long userId = AppThreadLocalUtil.getId();
        if (userId==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.删除
        Query query = Query.query(Criteria.where("userId").is(userId).and("id").is(dto.getId()));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
